package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.common.R;
import com.reggie.dto.DishDto;
import com.reggie.entity.Category;
import com.reggie.entity.Dish;
import com.reggie.entity.DishFlavor;
import com.reggie.service.CategoryService;
import com.reggie.service.DishFlavorService;
import com.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/*
 * 菜品管理（以及风味）
 * */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    /*
     * 新增菜品
     *
     * 注意：新增菜品包含了Dish和Dishflavor，所以需要一个dto（数据传输对象）来将封装
     * */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("新增菜品：{}", dishDto.toString());
        dishService.saveWithDishFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /*
     * 菜品分页查询
     * */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //过滤条件
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoInfo, "records");

        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            Long categoryId = dish.getCategoryId();//分类id
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoInfo.setRecords(list);

        return R.success(dishDtoInfo);

    }

    /*
     * 根据id查询菜品信息和对应的口味信息
     * */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }

    /*
     * 更新菜品
     *
     * 注意：新增菜品包含了Dish和Dishflavor，所以需要一个dto（数据传输对象）来将封装
     * */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("修改菜品：{}", dishDto.toString());
        dishService.updateWithDishFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /*
     * 根据条件查询菜品
     * */
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId())
                        .eq(Dish::getStatus,1);//1为起售状态
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        queryWrapper.like(dish.getName()!=null, Dish::getName,dish.getName());
        List<Dish> list = dishService.list(queryWrapper);
        return R.success(list);
    }*/
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
                .eq(Dish::getStatus, 1);//1为起售状态
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        queryWrapper.like(dish.getName() != null, Dish::getName, dish.getName());
        List<Dish> list = dishService.list(queryWrapper);
        List<DishDto> dishDtos = list.stream().map(new Function<Dish, DishDto>() {
            @Override
            public DishDto apply(Dish dish) {
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(dish, dishDto);
                Long categoryId = dish.getCategoryId();//分类id
                Category category = categoryService.getById(categoryId);
                if (category != null) {
                    String categoryName = category.getName();
                    dishDto.setCategoryName(categoryName);
                }
                //查询口味
                Long id = dish.getId();//菜品id
                //查询口味
                LambdaQueryWrapper<DishFlavor> dishFlavorQueryWrapper = new LambdaQueryWrapper<>();
                dishFlavorQueryWrapper.eq(id != null, DishFlavor::getDishId, id);
                List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorQueryWrapper);
                dishDto.setFlavors(dishFlavors);
                return dishDto;
            }
        }).collect(Collectors.toList());
        return R.success(dishDtos);
    }

    /*
    * 更新菜品状态
    * */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        log.info("修改的状态为：{}，需要批量修改的id：{}",status,ids.toString());
        LambdaUpdateWrapper<Dish> updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.in(Dish::getId,ids).set(Dish::getStatus,status);
        dishService.update(updateWrapper);
        return R.success("批量修改状态成功");
    }

    /*
    *  删除菜品，同时如果套餐中有改菜品，将套餐停售
    * */
    @DeleteMapping
    public R<String> batchDelete(@RequestParam List<Long> ids){
        log.info("需要删除的菜品id为：{}",ids.toString());
        R<String> stringR = dishService.batchDelete(ids);
        return stringR;
    }
}
